<template>
    <div class="ai-index">
        <el-scrollbar>
            <div class="container" v-if="messages.length > 0">
                <div v-for="(msg, index) in messages" :key="index" class="message">
                    <div class="username" v-if="msg.type === 'user'">
                        <p>{{ msg.content }}</p>
                        <img :src="userStore.userInfo.image" v-if="userStore.userInfo.image" alt="用户头像">
                        <img src="@/assets/images/shouhu.png" v-else alt="默认头像">
                    </div>
                    <div class="chat-box" v-if="msg.type === 'assistant'">
                        <img src="@/assets/images/shouhu.png"
                            alt="助手头像">
                        <p>{{ msg.content }}</p>
                    </div>
                </div>
            </div>
            <div v-else>
                <el-empty description="description" />
            </div>
        </el-scrollbar>
        <div class="send-box">
            <el-autocomplete v-model="state" :fetch-suggestions="querySearch" clearable placeholder="请输入你要问的问题"
                @select="handleSelect" />
            <el-button color="#626aef" plain @click="sendMessage">发送</el-button>
        </div>
    </div>
</template>

<script setup>
import router from '@/router';
import { onMounted, ref, onUnmounted } from 'vue';
import { useUserStore } from '@/stores/user';

// 实例化仓库
const userStore = useUserStore()

const state = ref('');
const messages = ref([]); // 存储消息记录
const restaurants = ref([]);

const querySearch = (queryString, cb) => {
    const results = queryString
        ? restaurants.value.filter(createFilter(queryString))
        : restaurants.value;
    cb(results);
};

const createFilter = (queryString) => {
    return (restaurant) => 
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
}

const handleSelect = (item) => {
    state.value = item.value;
};

const loadAll = () => {
    return [
        { value: '请你自我介绍一下' },
    ];
};

const sendMessage = async () => {
    if (!state.value) return; // 如果输入为空则不发送
    // 记录用户消息
    messages.value.push({ type: 'user', content: state.value, reserve: true });
    try {
        const response = await fetch(`http://localhost:7070/api/admin/chat?input==${encodeURIComponent(state.value)}`, {
            method: 'GET',
            headers: {
                token: userStore.viewToken
            }
        });
        if (!response.ok) {
            if (response.status === 401) {
                router.push('/login');
            }
            throw new Error('网络响应出现问题');
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8");
        let result = '';

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            result += decoder.decode(value, { stream: true });

            // 判断reserve是否为false，如果为false则删除该消息
            const index = messages.value.findIndex(msg => msg.reserve === false);
            if (index !== -1) {
                messages.value.splice(index, 1);
            }
            // 记录助手消息
            messages.value.push({ type: 'assistant', content: result, reserve: false  });
        }
        // 获取最后的reserve，改成true
        const lastIndex = messages.value.length - 1;
        messages.value[lastIndex].reserve = true;
        // 一坨屎代码，但是我也不知道怎么优化

        state.value = ''; // 清空输入框

    } catch (error) {
        console.error('请求出错:', error);
    }
};

onMounted(() => {
    restaurants.value = loadAll();
});
// 页面卸载时清空消息
onUnmounted(() => {
    messages.value = [];
});
</script>


<style lang="scss">
.ai-index {
    box-sizing: border-box;
    width: 100%;
    background-color: #f9f9f9; // 更柔和的背景
    border: 1px solid #999;
    display: flex;
    flex-direction: column;
    height: 85vh; // 或者设置一个适当的高度

    .container {
        width: 100%;

        .username {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            // text-align: right;

            img {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                margin: 0 10px;
            }

            p {
                max-width: 70%;
                display: grid;
                justify-items: end;
                background-color: #e1ffc7;
                padding: 5px;
                border-radius: 5px;
            }
        }

        .chat-box {
            display: flex;
            align-items: center;

            img {
                width: 50px;
                height: 50px;
                border-radius: 50%;
                margin: 0 10px;
            }

            p {
                max-width: 70%;
                padding: 5px;
                background-color: #e2e6de;
                border-radius: 5px;
            }
        }
    }

    .send-box {
        margin-top: auto;
        width: 100%;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 10px;

        .el-autocomplete {
            margin-left: 10px;

            .el-input {
                height: 50px;
            }
        }

        .el-button {
            margin: 0 10px;
            height: 50px;
        }
    }
}
</style>
